package team.first.movieapiv2pro.controller;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import team.first.movieapiv2pro.domain.User;
import team.first.movieapiv2pro.service.AuthorizationService;
import team.first.movieapiv2pro.token.Token;
import team.first.movieapiv2pro.vo.ApiResponse;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: HAPPY
 * @Project_name: project
 * @Package_name: team.first.movieapiv1pro.controller
 * @Date: 2021/12/24 15:32
 * @Description:
 */
@RestController
public class AuthorizationController {

    @Autowired
    private AuthorizationService authorizationService;

    @GetMapping("/api/v2/authorization")
    public ApiResponse<Token> authorization(HttpServletRequest request) {
        ApiResponse apiResponse = new ApiResponse();
        int flag = (int) request.getSession().getAttribute("flag");
        switch (flag) {
            case 0 -> apiResponse.setCode(401).setSuccess(false).setMessage("未认证");
            case 1 -> apiResponse.setCode(403).setSuccess(false).setMessage("认证失败");
        }
        return apiResponse;
    }

    /**
     * 2.1 POST 用户注册接口
     *
     * @param user 要注册的用户的部分信息
     * @return 返回注册后的用户的全部信息，也就只是多个个自增id
     */
    @PostMapping("/api/v2/register")
    @ApiOperation("2.1 POST 用户注册接口")
    public ApiResponse<Object> register(@ApiParam("要注册的用户信息") User user) {
        ApiResponse<Object> apiResponse = new ApiResponse<>();
        int res = authorizationService.register(user);
        if (res == 0) {
            apiResponse.setCode(200).setSuccess(true).setMessage("注册成功").setData(user);
        } else {
            if (res == 1) {
                apiResponse.setCode(500).setSuccess(false).setMessage("注册失败").setData("服务器异常");
            } else {
                apiResponse.setCode(500).setSuccess(false).setMessage("注册失败").setData("邮箱已存在");
            }
        }

        return apiResponse;
    }

    /**
     * 用户登录（认证）接口
     *
     * @param user 登录（认证）的用户信息
     * @return 返回认证令牌
     */
    @PostMapping("/api/v2/login")
    public ApiResponse<Token> auth(User user) {
        ApiResponse<Token> apiResponse = new ApiResponse<>();

        Token token = authorizationService.login(user);
        if (token != null) {
            apiResponse.setData(token).setCode(200).setMessage("认证成功").setSuccess(true);
        } else {
            apiResponse.setSuccess(false).setCode(500).setMessage("认证失败");
        }

        return apiResponse;
    }
}
